# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

class ArgumentError(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return self.msg

class CmdBase(object):

    # Commands are static.
    __init__ = None
    aliases = None

    @classmethod
    def docstr(cls):
        return cls.__doc__ or "No help available"

    @classmethod
    def shorthelp(cls):
        return cls.docstr().split('\n')[0]

    @classmethod
    def longhelp(cls):
        longhelp = [ "Command: %s" % cls.name ]

        if cls.aliases:
            longhelp.append("Aliases: %s" % ', '.join(cls.aliases))

        longhelp.append("")
        longhelp.append(cls.docstr())

        return '\n'.join(longhelp)

    @classmethod
    def invalid_args(cls, msg):
        raise ArgumentError(msg)

    @classmethod
    def fspath(cls, path):
        abspath = os.path.abspath(path)
        parts = abspath.split('/')

        for i in range(len(parts)):
            subpath = '/'.join(parts[:i+1]) + "/.mfilesfs"
            if os.path.isdir(subpath):
                return '/'.join(parts[:i+1]), '/' + '/'.join(parts[i+1:])

                
